package com.snailxr.base.task.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.snailxr.base.support.RetObj;
import com.snailxr.base.task.domain.APIObj;
import com.snailxr.base.task.service.APIService;

@Controller
@RequestMapping("/api")
public class APIController {
	// 日志记录器
	public final Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private APIService apiService;
	
	@RequestMapping("apiList")
	public String apiList(HttpServletRequest request){
		List<APIObj> apiList = apiService.selectAll();
		log.debug(apiList.toString());
		request.setAttribute("apiList", apiList);
		return "base/api/apiList";
	}
	
	//1、@Validated作用就是将pojo内的注解数据校验规则(@NotNull等)生效，如果没有该注解的声明，pojo内有注解数据校验规则也不会生效
	//2、BindingResult对象用来获取校验失败的信息(@NotNull中的message)，与@Validated注解必须配对使用，一前一后
	@RequestMapping("add")
	@ResponseBody
	public RetObj add(HttpServletRequest request,@Validated APIObj apiObj,BindingResult result){
		RetObj retObj = new RetObj();
		//数据验证
		if(result.hasErrors()){
			List<ObjectError> allErrors = result.getAllErrors();
			String message = "";
			for(ObjectError objectError : allErrors){
				message += objectError.getDefaultMessage();
			}
			log.error(message);
			retObj.setMsg(message);
		}else{
			try{
				apiService.add(apiObj);
				retObj.setMsg("保存成功！");
			}catch(Exception e){
				retObj.setMsg("保存失败！");
			}
		}
		return retObj;
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public RetObj delete(HttpServletRequest request,int apiId){
		RetObj retObj = new RetObj();
		//TODO 还需要做数据验证
		try{
			APIObj apiObj = apiService.getByApiId(apiId);
			log.debug("@@@@@@@@@@@@@@"+apiObj);
			apiService.delete(apiObj);
			retObj.setMsg("删除成功！");
		}catch(Exception e){
			retObj.setMsg("删除失败！");
		}
		return retObj;
	}
}
